package com.azzcs.mvc.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author: wzg
 * @Date: 2020/12/28 下午4:20
 */
public class HandlerExecutionChain {
    private HandlerMethod handler;
    private List<HandlerInterceptor> interceptorList;

    public HandlerExecutionChain(HandlerMethod handler, List<HandlerInterceptor> interceptorList) {
        this.handler = handler;
        this.interceptorList = interceptorList;
    }

    public HandlerMethod getHandler() {
        return handler;
    }


    /**
     *  执行 拦截器 前置
     * @param req
     * @param resp
     * @param handler
     */
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, HandlerMethod handler) {
        for (HandlerInterceptor handlerInterceptor : interceptorList) {
            if(!handlerInterceptor.preHandle(req, resp, handler)){
                this.afterCompletion(req,resp,handler);
                return false;
            }
        }
        return true;
    }
    /**
     *  执行 拦截器 后置
     * @param req
     * @param resp
     * @param handler
     */
    public void postHandle(HttpServletRequest req, HttpServletResponse resp, HandlerMethod handler) {
        for (int i = interceptorList.size() - 1; i >= 0; i--) {
            interceptorList.get(i).postHandle(req,resp,handler);
        }
    }

    public void afterCompletion(HttpServletRequest req, HttpServletResponse resp, HandlerMethod handler) {
        for (int i = interceptorList.size() - 1; i >= 0; i--) {
            interceptorList.get(i).afterCompletion(req,resp,handler);
        }
    }
}
